package ru.hh.team02.chat.client;

import ru.hh.team02.chat.server.ChatServer;
// XXX [Oleg] The biggest problem here is that we don't process the situations where
// the recipient may not exist or be mistyped. I think we should respond to such messages
// to the sender and log appropriately.
/**
 * Class with methods to handle messages.
 */
public class MessageHandler {
    private String clientName;

    /**
     *
     * @param clientName Client name the messages are addressed to.
     */
    public MessageHandler(String clientName) {
        this.clientName = clientName;
    }

    /**
     * Mark message in the DB as delivered or delete (depends on implementation)
     * for it to not longer be sent to the user on their login.
     * @param message Unparsed status message.
     */
    public void markMessageInDb(String message) {
        // XXX [Oleg] Shouldn't we catch parsing errors and log them?
        int messageId = Integer.parseInt(message.split(" ")[1]);
        ChatServer.dbService.markPersonalMessageAsDelivered(messageId);
    }

    /**
     * Handle message to change room.
     * @param message Unparsed message.
     */
    // XXX [Oleg] should we return false if operation failed or if the room doesn't exist?
    public void changeRoom(String message) {
        String[] info = message.split(" ");
        if (info.length == 2) {
            String roomName = info[1];

            ChatServer.REGISTRY.changeRoom(clientName, roomName);
            // XXX [Oleg] What if this failed? Shouldn't we log a different thing?
            ChatServer.ADMIN_LOGGER.write("Client \"" + clientName
                    + "\" entered in new room \"" + roomName + "\"");
        }
    }

    /**
     * Send personal message to the client specified inside the message.
     * @param message Unparsed private message.
     */
    // XXX [Oleg] What if we fail to send it? E.g. recipient doesn't exist, etc.
    public void sendPersonalMessage(String message) {
        String[] info = message.split(" ", 3);
        if (info.length == 3) {
            String recepientName = info[1];
            String messageText = info[2];


            ChatServer.MESSENGER.SendPersonalMessage("personal:" + clientName + "> " +
                    messageText,
                    recepientName);
            ChatServer.ADMIN_LOGGER.write("Client \"" + clientName
                    + "\" sent new message: \""
                    + message + "\"");
        }
    }

    /**
     * Send the message to the room the client this handler belongs to is in.
     * @param message Message to send.
     */
    public void sendMessageToRoom(String message) {
        ChatServer.MESSENGER.sendMessageToRoom(clientName + "> " + message,
                clientName);
        ChatServer.ADMIN_LOGGER.write("Client \"" + clientName
                + "\" sent new message: \"" + message + "\"");
    }

}
